/**
 * JDBM LICENSE v1.00
 *
 * Redistribution and use of this software and associated documentation
 * ("Software"), with or without modification, are permitted provided
 * that the following conditions are met:
 *
 * 1. Redistributions of source code must retain copyright
 *    statements and notices.  Redistributions must also contain a
 *    copy of this document.
 *
 * 2. Redistributions in binary form must reproduce the
 *    above copyright notice, this list of conditions and the
 *    following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. The name "JDBM" must not be used to endorse or promote
 *    products derived from this Software without prior written
 *    permission of Cees de Groot.  For written permission,
 *    please contact cg@cdegroot.com.
 *
 * 4. Products derived from this Software may not be called "JDBM"
 *    nor may "JDBM" appear in their names without prior written
 *    permission of Cees de Groot.
 *
 * 5. Due credit should be given to the JDBM Project
 *    (http://jdbm.sourceforge.net/).
 *
 * THIS SOFTWARE IS PROVIDED BY THE JDBM PROJECT AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * CEES DE GROOT OR ANY CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Copyright 2000 (C) Cees de Groot. All Rights Reserved.
 * Contributions are Copyright (C) 2000 by their associated contributors.
 *
 * $Id: RecordFile.java,v 1.6 2005/06/25 23:12:32 doomdark Exp $
 */

package com.sunchangming.stmdb.recman;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Iterator;

/**
 * This class represents a random access file as a set of fixed size records.
 * Each record has a physical record number, and records are cached in order to
 * improve access.
 * <p>
 * The set of dirty records on the in-use list constitutes a transaction. Later
 * on, we will send these records to some recovery thingy.
 */
public final class RecordFile {
	final TransactionManager txnMgr;

	// inUse -> dirty -> inTxn -> free
	private final HashMap<Long, BlockIo> inUse = new HashMap<Long, BlockIo>();
	private final HashMap<Long, BlockIo> dirty = new HashMap<Long, BlockIo>();
	private final HashMap<Long, BlockIo> inTxn = new HashMap<Long, BlockIo>();

	/** The length of a single block. */
	public final static int BLOCK_SIZE = 8192;// 4096;

	/** The extension of a record file */
	final static String extension = ".db";

	/** A block of clean data to wipe clean pages. */
	final static byte[] cleanData = new byte[BLOCK_SIZE];

	private SeekableByteChannel file;

	/**
	 * 文件名，不含后缀名（extension）。
	 */
	private final String fileName;

	/**
	 * Creates a new object on the indicated filename. The file is opened in
	 * read/write mode.
	 * 
	 * @param fileName
	 *            the name of the file to open or create, without an extension.
	 * @throws IOException
	 *             whenever the creation of the underlying RandomAccessFile
	 *             throws it.
	 */
	RecordFile(String fileName) throws IOException {
		this.fileName = fileName;
		final java.nio.file.Path path = java.nio.file.Paths.get(fileName + extension);
		this.file = java.nio.file.Files.newByteChannel(path, StandardOpenOption.READ, StandardOpenOption.WRITE,
				StandardOpenOption.CREATE);
		this.txnMgr = new TransactionManager(this);
	}

	/**
	 * Returns the file name.
	 */
	String getFileName() {
		return fileName;
	}

	/**
	 * Gets a block from the file. The returned byte array is the in-memory copy
	 * of the record, and thus can be written (and subsequently released with a
	 * dirty flag in order to write the block back).
	 * 
	 * inTxn -> dirty -> free
	 * 
	 * @param blockid
	 *            The record number to retrieve.
	 */
	BlockIo get(long blockid) throws IOException {
		final Long key = Long.valueOf(blockid);

		// try in transaction list, dirty list, free list
		BlockIo node = inTxn.get(key);
		if (node != null) {
			inTxn.remove(key);
			inUse.put(key, node);
			return node;
		}

		node = dirty.get(key);
		if (node != null) {
			dirty.remove(key);
			inUse.put(key, node);
			return node;
		}

		// sanity check: can't be on in use list
		if (inUse.get(key) != null) {
			throw new Error("double get for block " + blockid);
		}
		final BlockIo retval = new BlockIo(blockid, new byte[BLOCK_SIZE]);

		//分配一个新的node
		node = retval;
		final long offset = blockid * BLOCK_SIZE;
		//如果在当前文件的大小范围内
		if (file.size() > 0 && offset <= file.size()) {
			//那就读出来
			read(file, offset, node.getData(), BLOCK_SIZE);
		}
		inUse.put(key, node);
		node.setClean();
		return node;
	}

	/**
	 * Releases a block.
	 * 
	 * @param blockid
	 *            The record number to release.
	 * @param isDirty
	 *            If true, the block was modified since the get().
	 */
	void release(long blockid, boolean isDirty) throws IOException {
		final BlockIo node = inUse.get(Long.valueOf(blockid));
		if (node == null)
			throw new IOException("bad blockid " + blockid + " on release");
		if (!node.isDirty() && isDirty)
			node.setDirty();
		release(node);
	}

	/**
	 * 将一个block释放。
	 * 
	 * @param block
	 */
	void release(BlockIo block) {
		final Long key = Long.valueOf(block.getBlockId());
		//从inUse移除
		inUse.remove(key);
		//如果是脏的，挪到dirty中
		if (block.isDirty()) {
			dirty.put(key, block);
		} else {
			//如果是干净的并且在事务中，那么挪到inTxn中。
			if (block.isInTransaction()) {
				inTxn.put(key, block);
			}
		}
	}

	/**
	 * 直接丢掉一个block，不管它是不是干净的，也不管是否在事务中
	 * 
	 * @param block
	 */
	void discard(BlockIo block) {
		final Long key = Long.valueOf(block.getBlockId());
		inUse.remove(key);
	}

	void commit() throws IOException {
		//XXX:这个&&得去掉吧？判断一次就够了
		if (!inUse.isEmpty() && inUse.size() > 1) {
			showList(inUse.values().iterator());
			throw new Error("in use list not empty at commit time (" + inUse.size() + ")");
		}

		if (dirty.isEmpty()) {
			return;
		}

		txnMgr.start();
		for (final Iterator<BlockIo> i = dirty.values().iterator(); i.hasNext();) {
			final BlockIo node = i.next();
			i.remove();
			txnMgr.add(node);
			inTxn.put(node.getBlockId(), node);
		}
		txnMgr.commit();
	}

	/**
	 * Rollback the current transaction by discarding all dirty buffers
	 */
	void rollback() throws IOException {
		// debugging...
		if (!inUse.isEmpty()) {
			showList(inUse.values().iterator());
			throw new Error("in use list not empty at rollback time (" + inUse.size() + ")");
		}
		// System.out.println("rollback...");
		dirty.clear();

		txnMgr.synchronizeLogFromDisk();

		if (!inTxn.isEmpty()) {
			showList(inTxn.values().iterator());
			throw new Error("in txn list not empty at rollback time (" + inTxn.size() + ")");
		}
	}

	/**
	 * Commits and closes file.
	 */
	void close() throws IOException {
		if (!dirty.isEmpty()) {
			commit();
		}
		txnMgr.shutdown();

		if (!inTxn.isEmpty()) {
			showList(inTxn.values().iterator());
			throw new Error("In transaction not empty");
		}

		// these actually ain't that bad in a production release
		if (!dirty.isEmpty()) {
			System.out.println("ERROR: dirty blocks at close time");
			showList(dirty.values().iterator());
			throw new Error("Dirty blocks at close time");
		}
		if (!inUse.isEmpty()) {
			System.out.println("ERROR: inUse blocks at close time");
			showList(inUse.values().iterator());
			throw new Error("inUse blocks at close time");
		}

		// debugging stuff to keep an eye on the free list
		// System.out.println("Free list size:" + free.size());
		file.close();
		file = null;
	}

	/**
	 * Force closing the file and underlying transaction manager. Used for
	 * testing purposed only.
	 */
	void forceClose() throws IOException {
		txnMgr.forceClose();
		file.close();
	}

	/**
	 * Prints contents of a list
	 */
	private void showList(Iterator<?> i) {
		int cnt = 0;
		while (i.hasNext()) {
			System.out.println("elem " + cnt + ": " + i.next());
			cnt++;
		}
	}

	/**
	 * 把一个block写入到硬盘文件上。TODO:写失败的时候retry
	 * 
	 * @param node
	 * @throws IOException
	 */
	void synch(BlockIo node) throws IOException {
		final byte[] data = node.getData();
		if (data != null) {
			final long offset = node.getBlockId() * BLOCK_SIZE;
			file.position(offset);
			final int written = file.write(ByteBuffer.wrap(data));
			if (written != BLOCK_SIZE)
				throw new RuntimeException("page write fail");
		}
	}

	/**
	 * Releases a node from the transaction list, if it was sitting there.
	 * 
	 * @param recycle
	 *            true if block data can be reused
	 */
	void releaseFromTransaction(BlockIo node) throws IOException {
		final Long key = Long.valueOf(node.getBlockId());
		inTxn.remove(key);
	}

	/**
	 * Synchronizes the file.
	 */
	void sync() throws IOException {
		//TODO:
	}

	private static void read(SeekableByteChannel file2, long offset, byte[] buffer, int nBytes) throws IOException {
		file2.position(offset);
		final ByteBuffer bb = ByteBuffer.wrap(buffer);
		while (nBytes > 0) {
			final int read = file2.read(bb);
			if (read == -1) {
				bb.put(cleanData, 0, nBytes);
				break;
			}
			nBytes -= read;
		}
	}

}
